"""
定义一个方法 请求的公共方法

"""
import json

import requests

from utils.log_util import logger
from utils.read import base_data
from utils.response_util import process_response

api_dit_url1 = base_data.read_ini()['host']['api_dit_url1']
# api_dit_url_zhihui = base_data.read_ini()['host']['api_dit_url_zhihui']


# print(api_dit_url_zhihui + '/center/login/user-login-for-web')


class RestClient:
    def __init__(self,url):
        self.api_dit_url1 = url
        self.session = requests.Session()  # 接口通过后headers和cookie就会复制给self.session

    def get(self, url, **kwargs):
        return self.request(url, "GET", **kwargs)

    def post(self, url, **kwargs):
        """
        因为post请求的时候 位置参数第二个是data 所以requests请求的时候要加上json=json
        :param url:
        :param json:
        :param kwargs:
        :return:
        """
        return self.request(url, "POST", **kwargs)

    def put(self, url, **kwargs):
        return self.request(url, "PUT", **kwargs)

    def delete(self, url, **kwargs):
        return self.request(url, "DELETE", **kwargs)

    def request(self, url, method, **kwargs):
        self.request_log(url, method, **kwargs)
        if method == "GET":
            return self.session.get(self.api_dit_url1 + url, **kwargs)
            # return process_response(response)
        if method == "POST":
            return self.session.post(self.api_dit_url1 + url, **kwargs)
        if method == "PUT":
            return self.session.put(self.api_dit_url1 + url, **kwargs)
        if method == "DELETE":
            return self.session.delete(self.api_dit_url1 + url, **kwargs)
        # response = requests.request(method,self.api_root_url+ url,**kwargs)
        # return process_response(response)

    def request_log(self, url, method, **kwargs):

        data = dict(**kwargs).get("data")
        json_data = dict(**kwargs).get("json")
        params = dict(**kwargs).get("params")
        headers = dict(**kwargs).get("headers")
        # 当data和params为空时，不报错的方法
        # 打印接口请求的地址和方法参数等信息
        logger.info("接口请求的地址>>>{0}".format(self.api_dit_url1 + url))
        # logger.info("接口请求的地址>>>{0}".format(self.api_root_url + url))
        logger.info("接口请求的方法>>>{0}".format(method))

        # 判断有某个参数就打印某个日志，没有就不打印
        if data is not None:
            logger.info("接口请求的data参数>>>\n{0}".format(json.dumps(data,ensure_ascii=False,indent=2)))
        if json_data is not None:
            logger.info("接口请求的json参数>>>\n{0}".format(json_data,ensure_ascii=False, indent=2))  # 不定长参数里面提取出json,加n换行操作
        if params is not None:
            logger.info("接口请求的params参数>>>\n{0}".format(json.dumps(params,ensure_ascii=False, indent=2)))
        if headers is not None:
            logger.info("接口请求的headers参数>>>\n{}".format(json.dumps(headers, ensure_ascii=False, indent=2)))


Api = RestClient(api_dit_url1)
